package bupt.xixi.netty;

import bupt.xixi.entity.RpcResponse;
import bupt.xixi.enumeration.Codec;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClientHandler extends SimpleChannelInboundHandler<RpcResponse> {

    // 添加日志
    Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);


    @Override
    protected void channelRead0(ChannelHandlerContext context, RpcResponse rpcResponse) throws Exception {
        try {
            // 得到回调信息后，将其保存到attributeKey中
            logger.info(String.format("客户端收到消息： %s", rpcResponse));
            AttributeKey<RpcResponse> key = AttributeKey.valueOf("rpcResponse");
            context.channel().attr(key).set(rpcResponse);
            context.channel().close();
        } finally {
            // 释放byteBuf资源！
            ReferenceCountUtil.release(rpcResponse);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // super.userEventTriggered(ctx, evt);
        // 如果是空闲检测事件
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            switch (event.state()) {
                case READER_IDLE:
                    logger.info("太长时间没收到服务端回复的PONG了, 我要关闭连接啦");
                    // 如果是读异常 表明没收到PONG 大概时间设定为5倍吧
                    ctx.channel().close();
                case WRITER_IDLE:
                    break;
                case ALL_IDLE:
                    sendHeartMessage(ctx);
            }
        }
    }

    private void sendHeartMessage(ChannelHandlerContext ctx) {
        final Channel channel = ctx.channel();
        channel.write(Codec.MAGIC_NUMBER);
        channel.write(Codec.PackageType.HEART_PACK.getCode());
        channel.write(Codec.heartData.PING.getData());
        channel.flush(); // 直接flush没有经过decoding\encoding
    }
}
